// src/services/WebSocketService.js
import { ref, onMounted, onUnmounted } from 'vue';
import { getToken } from '@/utils/auth'; // 引入获取 Token 的方法
import { useMessageStore } from '@/store/messageStore';

const ws = ref(null);
let reconnectAttempts = 0;
const maxReconnectAttempts = 3;//最多从重连5次

export const connectWebSocket = () => {
  const token = getToken();
  if (!token) {
    console.error('WebSocket 连接失败：未获取到 Token');
    return;
  }

  console.log("socket方法")

  if (ws.value && [WebSocket.CONNECTING, WebSocket.OPEN].includes(ws.value.readyState)) {
    console.log('已有活跃连接');
    return;
  } // 防止重复连接

  const wsUrl = `ws://localhost:8081/ws?token=${token}&type=Admin`
  console.log('连接socket，wsUrl',wsUrl)

  ws.value = new WebSocket(wsUrl);

  ws.value.onopen = () => {
    console.log('WebSocket 已通道已建立！');
    reconnectAttempts = 0; // 重置重连计数器
  };

  ws.value.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data);
      // 触发全局事件总线
      window.$eventBus?.emit('message-received', message);
      // 更新 Pinia 存储
      const messageStore = useMessageStore();
      messageStore.addMessage(message);
    } catch (error) {
      console.error('消息解析失败:', error);
    }
  
  };

  ws.value.onerror = (error) => {
    console.error('WebSocket 错误:', error);
    // 可添加重连逻辑
  };

  ws.value.onclose = (event) => {
    console.log(`WebSocket 关闭，代码: ${event.code}，原因: ${event.reason}`);
    if (reconnectAttempts < maxReconnectAttempts) {
      setTimeout(() => {
        console.log(`尝试第 ${reconnectAttempts + 1} 次重连...`);
        connectWebSocket(); 
        reconnectAttempts++;
      }, 5000); // 5秒后重试
    }
  };
};

export const disconnectWebSocket = () => {
  if (ws.value) {
    ws.value.close();
    ws.value = null;
  }
};

export const sendMessage = (message) => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.send(JSON.stringify(message));
  }
};